package org.jeecg.modules.achexampaperquestionsitem.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.achexampaperquestionsitem.entity.AchExamPaperQuestionsItem;
import org.jeecg.modules.achexampaperquestionsitem.service.IAchExamPaperQuestionsItemService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.achexampaperquestionsitem.vo.AchExamPaperQuestionsItemVo;
import org.jeecg.modules.classes.entity.CouClass;
import org.jeecg.modules.common.api.ISysInfo;
import org.jeecg.modules.common.baseentity.BaseApiEntity;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: ach_exam_paper_questions_item
 * @author: baochangrong
 * @Date:   2022-03-18
 * @Version: V1.0
 */
@Api(tags="ach_exam_paper_questions_item")
@RestController
@RequestMapping("/achexampaperquestionsitem/achExamPaperQuestionsItem")
@Slf4j
public class AchExamPaperQuestionsItemController extends JeecgController<AchExamPaperQuestionsItem, IAchExamPaperQuestionsItemService> {
	@Autowired
	private IAchExamPaperQuestionsItemService achExamPaperQuestionsItemService;
	@Autowired
	private ISysBaseAPI sysBaseAPI;
	 @Autowired
	 private ISysInfo sysInfo;
	/**
	 * 分页列表查询
	 * @param achExamPaperQuestionsItem
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "ach_exam_paper_questions_item-分页列表查询")
	@ApiOperation(value="ach_exam_paper_questions_item-分页列表查询", notes="ach_exam_paper_questions_item-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(AchExamPaperQuestionsItem achExamPaperQuestionsItem,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) throws NoSuchFieldException {
		//组装vo以外的其他参数
		Map<String,String> queryParam = sysInfo.getMapQueryParamByReq(req);
		//获取当前登录用户信息 把租户 部门 身份 学期 学年等基本信息信息赋值克隆给vo
		BaseApiEntity baseApiEntity = sysInfo.querySysInfoCloneObj(req,achExamPaperQuestionsItem,false); //获取当前登录用户信息 把租户 部门 身份 学期 学年等基本信息信息赋值给vo

		QueryWrapper<AchExamPaperQuestionsItem> queryWrapper = QueryGenerator.initQueryWrapper(achExamPaperQuestionsItem, req.getParameterMap());
		Page<AchExamPaperQuestionsItem> page = new Page<AchExamPaperQuestionsItem>(pageNo, pageSize);
		IPage<AchExamPaperQuestionsItem> pageList = achExamPaperQuestionsItemService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/** 全部查询 附带关联名称 voList */
	 @AutoLog(value = "voList-分页列表查询")
	 @ApiOperation(value="voList-分页列表查询", notes="voList-分页列表查询")
	 @GetMapping(value = "/voList")
	 public Result<?> voList(AchExamPaperQuestionsItemVo achExamPaperQuestionsItemVo,
							 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
							 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
							 HttpServletRequest req) {

		 //组装vo以外的其他参数：一般不用
//		 Map<String,String> queryParam = sysInfo.getMapQueryParamByReq(req);

		 //获取当前登录用户信息 把租户 部门 身份 学期 学年等基本信息信息赋值克隆给vo
		 BaseApiEntity baseApiEntity = sysInfo.querySysInfoCloneObj(req,achExamPaperQuestionsItemVo,false); //获取当前登录用户信息 把租户 部门 身份 学期 学年等基本信息信息赋值给vo
		 achExamPaperQuestionsItemVo.setSysOrgCode(null);//(baseApiEntity.getSubDepSysOrgCodes());//把所有下級部門編碼給
		 achExamPaperQuestionsItemVo.setCreateTime(null);
		 achExamPaperQuestionsItemVo.setCreateBy(null);
		 achExamPaperQuestionsItemVo.setUpdateBy(null);
		 achExamPaperQuestionsItemVo.setUpdateTime(null);
		 //根据用户身份重新设置查询条件值，不同的用户身份查询过滤不同的数据：
		 //1.获取用户身份 userIdentity loginUser.getUserIdentity() 用户身份字典码user_identity， 3教师 4学生 5家长 6班级  1普通用户 2上级部门负责人
		 //2.获取用户id loginUser.getId()
		 //userIdentity 用户身份字典码user_identity， 3教师 4学生 5家长 6班级  1普通用户 2上级部门负责人
//		 achExamPaperQuestionsItemVo = reSetObjectValue(baseApiEntity, achExamPaperQuestionsItemVo);


		 achExamPaperQuestionsItemVo.setDelFlag(0);
		 Page<AchExamPaperQuestionsItemVo> page = new Page<AchExamPaperQuestionsItemVo>(pageNo, pageSize);
		 IPage<AchExamPaperQuestionsItemVo> pageList = achExamPaperQuestionsItemService.voList(page, achExamPaperQuestionsItemVo);
		 return Result.OK(pageList);
	 }
	
	/**
	 * 添加
	 * @param achExamPaperQuestionsItem
	 * @return
	 */
	@AutoLog(value = "ach_exam_paper_questions_item-添加")
	@ApiOperation(value="ach_exam_paper_questions_item-添加", notes="ach_exam_paper_questions_item-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody AchExamPaperQuestionsItem achExamPaperQuestionsItem, HttpServletRequest req) {
		//获取当前登录用户信息
		String token = req.getHeader(CommonConstant.X_ACCESS_TOKEN);
		String username = JwtUtil.getUsername(token);
		//		SysUser sysUser = sysUserService.getOneUser(username);// sysBaseAPI.getUserByName(username); 不能直接引用system模块，需使用APi调用
		LoginUser loginUser = sysBaseAPI.getUserByName(username); //.getUserById() 获取登录用户
		String tenantId = req.getHeader("tenant-id");//获取当前登录用户的租户id
		String sysOrgCode = loginUser.getOrgCode();//获取当前用户的当前的部门编码（不是id是编码）,该编码随前端切换

		if (achExamPaperQuestionsItem.getExaPapQueItemNo() == null){
			achExamPaperQuestionsItem.setExaPapQueItemNo(achExamPaperQuestionsItem.getExaPapQueItemOrder());
		}
		achExamPaperQuestionsItem.setTenantId(tenantId);
		achExamPaperQuestionsItem.setSysOrgCode(sysOrgCode);
		achExamPaperQuestionsItemService.save(achExamPaperQuestionsItem);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param achExamPaperQuestionsItem
	 * @return
	 */
	@AutoLog(value = "ach_exam_paper_questions_item-编辑")
	@ApiOperation(value="ach_exam_paper_questions_item-编辑", notes="ach_exam_paper_questions_item-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody AchExamPaperQuestionsItem achExamPaperQuestionsItem) {
		achExamPaperQuestionsItemService.updateById(achExamPaperQuestionsItem);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "ach_exam_paper_questions_item-通过id删除")
	@ApiOperation(value="ach_exam_paper_questions_item-通过id删除", notes="ach_exam_paper_questions_item-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		achExamPaperQuestionsItemService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "ach_exam_paper_questions_item-批量删除")
	@ApiOperation(value="ach_exam_paper_questions_item-批量删除", notes="ach_exam_paper_questions_item-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.achExamPaperQuestionsItemService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "ach_exam_paper_questions_item-通过id查询")
	@ApiOperation(value="ach_exam_paper_questions_item-通过id查询", notes="ach_exam_paper_questions_item-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		AchExamPaperQuestionsItem achExamPaperQuestionsItem = achExamPaperQuestionsItemService.getById(id);
		if(achExamPaperQuestionsItem==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(achExamPaperQuestionsItem);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param achExamPaperQuestionsItem
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, AchExamPaperQuestionsItem achExamPaperQuestionsItem) {
        return super.exportXls(request, achExamPaperQuestionsItem, AchExamPaperQuestionsItem.class, "ach_exam_paper_questions_item");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, AchExamPaperQuestionsItem.class);
    }


	 /**
	  * 快速添加试题 speedAdd
	  * @return
	  */
	 @AutoLog(value = "ach_exam_paper_questions_item-快速添加试题")
	 @ApiOperation(value="ach_exam_paper_questions_item-快速添加试题", notes="ach_exam_paper_questions_item-快速添加试题")
	 @PostMapping(value = "/speedAdd")
	 public Result<?> speedAdd(@RequestBody JSONObject speedAddParams, HttpServletRequest req) {
		 //获取当前登录用户信息
		 String token = req.getHeader(CommonConstant.X_ACCESS_TOKEN);
		 String username = JwtUtil.getUsername(token);
		 //		SysUser sysUser = sysUserService.getOneUser(username);// sysBaseAPI.getUserByName(username); 不能直接引用system模块，需使用APi调用
		 LoginUser loginUser = sysBaseAPI.getUserByName(username); //.getUserById() 获取登录用户
		 String tenantId = req.getHeader("tenant-id");//获取当前登录用户的租户id
		 String sysOrgCode = loginUser.getOrgCode();//获取当前用户的当前的部门编码（不是id是编码）,该编码随前端切换


		 //根据参数解析生成的数据(传过来的快速添加明细-数量、单题分数、单题时长、题型类型等....)
		 String examinationPaperId = speedAddParams.getString("examinationPaperId");//所属试卷id
		 String examPaperProjectItemId = speedAddParams.getString("examPaperProjectItemId");//上级题型id
		 String exaPapQueItemTtype = speedAddParams.getString("exaPapQueItemTtype");//题型类型
		 String startExaPapQueItemNo = speedAddParams.getString("startExaPapQueItemNo");//开始试题编号
		 String startExaPapQueItemOrder = speedAddParams.getString("startExaPapQueItemOrder");//开始试题顺序
		 Double exaPapQueItemFullMarks = Double.parseDouble(speedAddParams.getString("exaPapQueItemFullMarks"));//单题满分
		 Double proposalDuration = Double.parseDouble(speedAddParams.getString("proposalDuration"));//单题时长
		 int proItemNum = Integer.parseInt(speedAddParams.getString("proItemNum"));//要添加的题目数量
		 //开始根据参数存入试题基本信息（如：proItemNum = 20个，i从0开始-i<proItemNum = 20个）
		 for (int i = 0; i < proItemNum; i++) {
			 AchExamPaperQuestionsItem achExamPaperQuestionsItem= new AchExamPaperQuestionsItem();
			 achExamPaperQuestionsItem.setId(null);//先id置空
			 achExamPaperQuestionsItem.setExaminationPaperId(examinationPaperId);//试卷id
			 achExamPaperQuestionsItem.setExamPaperProjectItemId(examPaperProjectItemId);//题型分项id
			 achExamPaperQuestionsItem.setExaPapQueItemTtype(exaPapQueItemTtype);//题型类型
			 //试题编号，通过参数开始试题编号依次增加
			 Integer NoNum = (Integer.parseInt(startExaPapQueItemNo) + i);
			 achExamPaperQuestionsItem.setExaPapQueItemNo(NoNum.toString());
			 //试题顺序，通过参数开始试题顺序依次增加
			 Integer OrderNum = (Integer.parseInt(startExaPapQueItemOrder) + i);
			 achExamPaperQuestionsItem.setExaPapQueItemOrder(OrderNum.toString());
			 achExamPaperQuestionsItem.setExaPapQueItemFullMarks(exaPapQueItemFullMarks);//单题满分
			 achExamPaperQuestionsItem.setProposalDuration(proposalDuration);//单题时长

			 achExamPaperQuestionsItem.setDelFlag(0);//正常（0表示未删除,1表示删除）
			 achExamPaperQuestionsItem.setIzOpen(1);//是否启用(1是启用，0否停用)
			 achExamPaperQuestionsItem.setTenantId(tenantId);
			 achExamPaperQuestionsItem.setSysOrgCode(sysOrgCode);
		 	 achExamPaperQuestionsItemService.save(achExamPaperQuestionsItem);
		 }

		 return Result.OK("快速新增已完成！");
	 }

	 /**
	  *
	  * 有需要身份识别的业务需打开下方注释补充查询条件就可以了
	  * 根据业务需要设置查询参数，不同身份的用户不同的查询参数、得到不同的查询结果
	  * 注意：有些业务并不需要身份识别，有些业务必须识别身份:4学生用户只能查自己的数据不能查别人的，6班级用户只能查自己班级的数据不能查其他班级的数据，
	  * 3老师只能查老师所在部门和下级部门的数据，1普通用户（一般是非教学用户）
	  * @param baseApiEntity
	  * @return Object
	  */
	 private AchExamPaperQuestionsItemVo reSetObjectValue(BaseApiEntity baseApiEntity,AchExamPaperQuestionsItemVo achExamPaperQuestionsItemVo){
		 //1.获取用户身份 userIdentity loginUser.getUserIdentity() 用户身份字典码user_identity， 3教师 4学生 5家长 6班级  1普通用户 2上级部门负责人
		 //2.获取用户id loginUser.getId()
		 int userIdentity = baseApiEntity.getUserIdentity();//获取当前登录用户身份：字典码 user_identity，3教师 4学生 5家长 6班级  1普通用户 2上级部门负责人
		 String userId = baseApiEntity.getLoginUser().getId(); //当前登录用户id

		 //有需要身份识别的业务需打开下方注释补充查询条件就可以了
		 //根据业务需要设置查询参数，不同身份的用户不同的查询参数、得到不同的查询结果
		 //注意：有些业务并不需要身份识别，有些业务必须识别身份:4学生用户只能查自己的数据不能查别人的，6班级用户只能查自己班级的数据不能查其他班级的数据，3老师只能查老师所在部门和下级部门的数据，1普通用户（一般是非教学用户） 2上级部门负责人只能查所在部门和下级部门的数据

		 return achExamPaperQuestionsItemVo;
	 }

}
